<!--
  * 经销商对账
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form>
      <a-row :gutter="[8, 10]">
        <a-col :span="5.5">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="订单状态" class="smart-margin-bottom0">
            <EnumSelect enum-name="PROGRESS_TUHO_ENUM" v-model:value="queryForm.status" placeholder="订单状态" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="订单类型" class="smart-margin-bottom0">
            <a-select v-model:value="queryForm.order_type" :dropdownMatchSelectWidth="false" placeholder="订单类型" allow-clear>
              <a-select-option value="sales">销售单</a-select-option>
              <a-select-option value="refund">退货单</a-select-option>
              <a-select-option value="exchange">换货单</a-select-option>
              <a-select-option value="book">订货单</a-select-option>
              <a-select-option value="book_refund">订退单</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="onExport" type="primary" v-privilege="'commission:dealer:export'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ fixed: true, hideSelectAll: true, selectedRowKeys: selectedRowKeys, onSelect: onSelectChange }" @expand="onExpand">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'name'">
            <template v-if="record.level === expandLevel.ORDER.value">
              <div class="order-name">
                <CopyText :text="text">
                  <a class="order-no" @click="detail(record)" :style="{ color: record.is_account === 2 ? 'green' : 'red' }">{{ text }}</a>
                </CopyText>
                <div class="order-tag">
                  <a-tag color="#87d068" v-if="record.order_type === 1">销售</a-tag>
                  <a-tag color="#108ee9" v-if="record.order_type === 2">退货</a-tag>
                  <a-tag color="#2db7f5" v-if="record.order_type === 3">换货</a-tag>
                  <a-tag color="#2db166" v-if="record.order_type === 4">订货</a-tag>
                  <a-tag color="#1667f5" v-if="record.order_type === 5">订退</a-tag>
                  <a-tag color="#f50" v-if="record.is_abnormal === 2">异常</a-tag>
                </div>
              </div>
              <div>
                {{ record.store_name }}
              </div>
            </template>
            <template v-if="record.level === expandLevel.DATE.value">
              <span>{{ text }}</span>
              <span>
                未交
                <span style="color: #f00; font-weight: bold">{{ _.filter(record.children, { is_account: 1 }).length }}</span>
              </span>
            </template>
          </template>
          <template v-if="column.dataIndex === 'is_account' && record.level === expandLevel.ORDER.value">
            <a-tag color="#87d068" v-if="record.is_account === 2">已交账</a-tag>
            <a-tag color="#f50" v-if="record.is_account === 1">未交账</a-tag>
          </template>
          <template v-if="column.dataIndex === 'settlement'">
            <span>{{ Number(text).toFixed(2) }}</span>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell>已选</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>{{ Number(selectedSummary.order_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ Number(selectedSummary.total_received_money).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ Number(selectedSummary.advance_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ Number(selectedSummary.credit_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ Number(selectedSummary.cash_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ Number(selectedSummary.company_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ Number(selectedSummary.gift_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ Number(selectedSummary.cash_pledge_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ Number(selectedSummary.abnormal_amount).toFixed(2) }}</span>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ Number(selectedSummary.total_operation_fee).toFixed(2) }}</span>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ Number(selectedSummary.settlement).toFixed(2) }}</span>
              </a-table-summary-cell>
            </a-table-summary-row>
            <a-table-summary-row>
              <a-table-summary-cell>合计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>{{ isNaN(Number(totalSummary.order_amount)) ? '0.00' : Number(totalSummary.order_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ isNaN(Number(totalSummary.total_received_money)) ? '0.00' : Number(totalSummary.total_received_money).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ isNaN(Number(totalSummary.advance_amount)) ? '0.00' : Number(totalSummary.advance_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ isNaN(Number(totalSummary.credit_amount)) ? '0.00' : Number(totalSummary.credit_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ isNaN(Number(totalSummary.cash_amount)) ? '0.00' : Number(totalSummary.cash_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ isNaN(Number(totalSummary.company_amount)) ? '0.00' : Number(totalSummary.company_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ isNaN(Number(totalSummary.gift_amount)) ? '0.00' : Number(totalSummary.gift_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>{{ isNaN(Number(totalSummary.cash_pledge_amount)) ? '0.00' : Number(totalSummary.cash_pledge_amount).toFixed(2) }}</a-table-summary-cell>
              <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ isNaN(Number(totalSummary.abnormal_amount)) ? '0.00' : Number(totalSummary.abnormal_amount).toFixed(2) }}</span>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ isNaN(Number(totalSummary.total_operation_fee)) ? '0.00' : Number(totalSummary.total_operation_fee).toFixed(2) }}</span>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ isNaN(Number(totalSummary.settlement)) ? '0.00' : Number(totalSummary.settlement).toFixed(2) }}</span>
              </a-table-summary-cell>
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>

    <DriverDetailsModal ref="detailRef" />
  </a-card>
</template>
<script setup lang="ts">
import _ from 'lodash'
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import DriverDetailsModal from './components/driver-details-modal.vue'
import { commissionApi } from '@/api/business/finance/commission-api'
import TableOperator from '@/components/support/table-operator/index.vue'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { TIME_RANGE_PRESETS } from '@/constants/system/common-const'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useResize } from '@/hooks/web/use-resize-hook'
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize({ pagination: false })

// ---------------------------- 表格列 ----------------------------
const columns = ref([
  {
    title: '',
    dataIndex: 'expand',
    width: 30
  },
  {
    title: '日期',
    dataIndex: 'name',
    width: 320
  },
  {
    title: '交账状态',
    dataIndex: 'is_account'
  },
  {
    title: '订单金额',
    dataIndex: 'order_amount'
  },
  {
    title: '实际签收金额',
    dataIndex: 'accctual_received_money'
  },
  {
    title: '预付款',
    dataIndex: 'advance_amount'
  },
  {
    title: '欠款',
    dataIndex: 'credit_amount'
  },
  {
    title: '现金',
    dataIndex: 'cash_amount'
  },
  {
    title: '公户收款',
    dataIndex: 'company_amount'
  },
  {
    title: '0元赠',
    dataIndex: 'gift_amount'
  },
  {
    title: '押金',
    dataIndex: 'cash_pledge_amount'
  },
  {
    title: '异常金额',
    dataIndex: 'abnormal_amount'
  },
  {
    title: '服务金额',
    dataIndex: 'total_operation_fee'
  },
  {
    title: '结算金额',
    dataIndex: 'settlement'
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------

// 定义折叠层级
const expandLevel = {
  DATE: {
    value: 1,
    prefix: 'date_'
  },
  ORDER: {
    value: 2,
    prefix: 'order_'
  }
}

function transformData(data) {
  return (data || []).map((dateItem) => {
    const dateNode = {
      ...dateItem,
      name: dateItem.date,
      key: `${expandLevel.DATE.prefix}${dateItem.date}`,
      level: expandLevel.DATE.value,
      children: Array.isArray(dateItem.children)
        ? dateItem.children.map((orderItem) => ({
            ...orderItem,
            name: orderItem.no,
            key: `${expandLevel.ORDER.prefix}${orderItem.no}`,
            p_key: `${expandLevel.DATE.prefix}${orderItem.no}`,
            level: expandLevel.ORDER.value
          }))
        : []
    }
    return dateNode
  })
}
const totalSummary = ref({
  order_amount: 0,
  total_received_money: 0,
  advance_amount: 0,
  credit_amount: 0,
  cash_amount: 0,
  company_amount: 0,
  gift_amount: 0,
  cash_pledge_amount: 0,
  abnormal_amount: 0,
  total_operation_fee: 0,
  settlement: 0
})

const { queryForm, queryData, tableData, tableLoading, resetQuery, onSearch } = useQuery({
  fetchDataApi: async ({ filter }) => {
    const data = { ...filter }
    const res = await commissionApi.dealerOrder({ ...data })
    const result = transformData(res.data.data)

    // 计算总计
    totalSummary.value = {
      order_amount: 0,
      total_received_money: 0,
      advance_amount: 0,
      credit_amount: 0,
      cash_amount: 0,
      company_amount: 0,
      gift_amount: 0,
      cash_pledge_amount: 0,
      abnormal_amount: 0,
      total_operation_fee: 0,
      settlement: 0
    }

    result?.forEach((dateItem) => {
      dateItem.children?.forEach((orderItem) => {
        totalSummary.value.order_amount += Number(orderItem.order_amount) || 0
        totalSummary.value.total_received_money += Number(orderItem.total_received_money) || 0
        totalSummary.value.advance_amount += Number(orderItem.advance_amount) || 0
        totalSummary.value.credit_amount += Number(orderItem.credit_amount) || 0
        totalSummary.value.cash_amount += Number(orderItem.cash_amount) || 0
        totalSummary.value.company_amount += Number(orderItem.company_amount) || 0
        totalSummary.value.gift_amount += Number(orderItem.gift_amount) || 0
        totalSummary.value.cash_pledge_amount += Number(orderItem.cash_pledge_amount) || 0
        totalSummary.value.abnormal_amount += Number(orderItem.abnormal_amount) || 0
        totalSummary.value.total_operation_fee += Number(orderItem.total_operation_fee) || 0
        totalSummary.value.settlement += Number(orderItem.settlement) || 0
      })
    })

    return {
      list: result,
      total: 0
    }
  },
  queryFormFilter: {
    create_time: TIME_RANGE_PRESETS.find((item) => item.key === 'today')?.value,
    order_type: null,
    status: null
  },
  queryFormOp: {}
})

// 展开行
function onExpand(expanded: boolean, record: any) {
  // 如果是折叠
  if (!expanded) return
  // 如果是展开
  if (record.children?.length > 0 || record.level === expandLevel.ORDER.value) return
}

onMounted(queryData)

// ---------------------------- 交账 ----------------------------
const selectedRowKeys = ref<string[]>([])
const selectedSummary = ref({
  order_amount: 0,
  total_received_money: 0,
  advance_amount: 0,
  credit_amount: 0,
  cash_amount: 0,
  company_amount: 0,
  gift_amount: 0,
  cash_pledge_amount: 0,
  abnormal_amount: 0,
  total_operation_fee: 0,
  settlement: 0
})
function onSelectChange(record: any, selected: boolean) {
  const key = record.key
  if (selected) {
    selectedRowKeys.value.push(key)
    selectedSummary.value.order_amount += Number(record.order_amount) || 0
    selectedSummary.value.total_received_money += Number(record.total_received_money) || 0
    selectedSummary.value.advance_amount += Number(record.advance_amount) || 0
    selectedSummary.value.credit_amount += Number(record.credit_amount) || 0
    selectedSummary.value.cash_amount += Number(record.cash_amount) || 0
    selectedSummary.value.company_amount += Number(record.company_amount) || 0
    selectedSummary.value.gift_amount += Number(record.gift_amount) || 0
    selectedSummary.value.cash_pledge_amount += Number(record.cash_pledge_amount) || 0
    selectedSummary.value.abnormal_amount += Number(record.abnormal_amount) || 0
    selectedSummary.value.total_operation_fee += Number(record.total_operation_fee) || 0
    selectedSummary.value.settlement += Number(record.settlement) || 0
  } else {
    const index = selectedRowKeys.value.indexOf(key)
    if (index !== -1) {
      selectedRowKeys.value.splice(index, 1) // 从选中数组中移除
    }
    selectedSummary.value.order_amount -= Number(record.order_amount) || 0
    selectedSummary.value.total_received_money -= Number(record.total_received_money) || 0
    selectedSummary.value.advance_amount -= Number(record.advance_amount) || 0
    selectedSummary.value.credit_amount -= Number(record.credit_amount) || 0
    selectedSummary.value.cash_amount -= Number(record.cash_amount) || 0
    selectedSummary.value.company_amount -= Number(record.company_amount) || 0
    selectedSummary.value.gift_amount -= Number(record.gift_amount) || 0
    selectedSummary.value.cash_pledge_amount -= Number(record.cash_pledge_amount) || 0
    selectedSummary.value.abnormal_amount -= Number(record.abnormal_amount) || 0
    selectedSummary.value.total_operation_fee -= Number(record.total_operation_fee) || 0
    selectedSummary.value.settlement -= Number(record.settlement) || 0
  }
  console.log(selectedSummary.value)
}

const detailRef = ref()
function detail(record) {
  detailRef.value.showDrawer(record)
}
// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const data = {
    create_time: queryForm.value.create_time,
    order_type: queryForm.value.order_type,
    status: queryForm.value.status,
    export: 1
  }
  commissionApi.exportOrder(data)
}
</script>
<style lang="less" scoped>
.order-name {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.order-no {
  width: 225px;
}
.order-tag {
  flex: auto;
  display: flex;
  justify-content: start;
  align-items: center;
  margin-left: 10px;
  gap: 4px;
}
</style>
